import { getCartList } from "api/api";
export default {
    state: {
        cartInfoList: []
    },
    getters: {
        totalCheckedNum(state) {
            let count = 0;
            state.cartInfoList.forEach(item => {
                if (item.isChecked === 1) {
                    count += (+item.skuNum)
                }
            });
            return count
        },
        totalcheckedPrice(state) {
            let price = 0;
            state.cartInfoList.forEach((item) => {
                if (item.isChecked === 1) {
                    price += (+item.skuNum) * (+item.skuPrice)
                }
            })
            //全选状态
            return price
        },
        checkAll(state) {
            //计算出cartInfoList中有多少个选中的数据
            /*let count = state.cartInfoList.reduce(
                (adder,item)=> item.isChecked===`1`?adder+1:adder,0
            )*/
            let count = 0;
            state.cartInfoList.forEach((item) => {
                if (item.isChecked === 1) {
                    count++
                }
            })
            //全选状态
            return (count === state.cartInfoList.length) && (state.cartInfoList.length !== 0)
        },

        //所有选中的id
        checkAllIds(state) {
            let ids = [];
            state.cartInfoList.forEach((item) => {
                if (item.isChecked === 1) {
                    ids.push(item.skuId)
                }
            })
            //全选状态
            return ids
        },

        //所有选中的id
        noCheckAllIds(state) {
            let ids = [];
            state.cartInfoList.forEach((item) => {
                if (item.isChecked === 0) {
                    ids.push(item.skuId)
                }
            })
            //全选状态
            return ids
        },

    },
    mutations: {
        getCartList(state, cartInfoList) {
            state.cartInfoList = cartInfoList
        },

    },
    actions: {
        async getCartList(store) {
            try {
                const { code, data: [info] } = await getCartList();
                if (code === 200) {
                    let cartInfoList = [];
                    if (info) cartInfoList = info.cartInfoList

                    store.commit("getCartList", info.cartInfoList)
                }
                return { code, data: info }
            } catch (e) {
                return Promise.reject(e)
            }
        }
    }
}